/*
 * @Description: 对话框组件
 * @Author: Rfan
 * @Date: 2023-02-01 10:19:03
 * @LastEditTime: 2023-02-01 16:59:13
 */

import { useRef, useState } from 'react';
import { Modal } from 'antd';
import Draggable from 'react-draggable';
import type { DraggableData, DraggableEvent } from 'react-draggable';
import type { ModalProps } from 'antd/lib/modal/Modal';

export interface JPModalProps extends ModalProps {
  draggable?: boolean;
}

/** 对话框函数组件 */
const JPModal = (props: JPModalProps) => {
  const { draggable = false, title, children, ...rest } = props;

  // 是否拖拽标志
  const [disabled, setDisabled] = useState(false);
  // 拖拽边界
  const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
  // 拖拽元素ref
  const draggleRef = useRef<HTMLDivElement>(null);

  /**
   * @description: 拖拽开始方法
   * @param {DraggableEvent} _event
   * @param {DraggableData} uiData
   */
  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }

    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y)
    });
  };

  return draggable ? (
    <Modal
      {...rest}
      title={
        <div
          style={{
            width: '100%',
            cursor: 'move'
          }}
          onMouseOver={() => {
            if (disabled) {
              setDisabled(false);
            }
          }}
          onMouseOut={() => {
            setDisabled(true);
          }}
          // fix eslintjsx-a11y/mouse-events-have-key-events
          // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
          onFocus={() => {}}
          onBlur={() => {}}
          // end
        >
          {title}
        </div>
      }
      modalRender={(modal) => (
        <div></div>
        // <Draggable
        //   disabled={disabled}
        //   bounds={bounds}
        //   onStart={(event, uiData) => onStart(event, uiData)}
        // >
        //   <div ref={draggleRef}>{modal}</div>
        // </Draggable>
      )}
    >
      {children}
    </Modal>
  ) : (
    <Modal {...rest} title={title}>
      {children}
    </Modal>
  );
};

export default JPModal;
